package experiment;

import ccm.component.image.ManualResizeableImageJPanel;

import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;

public class TcpClient
{
    public static void main(String[] args)
    {
        String temp;
        JFrame jFrame=new JFrame("112312");
        jFrame.setSize(900,300);
        jFrame.setLocationRelativeTo(null);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        ManualResizeableImageJPanel manualResizeableImageJPanel=new ManualResizeableImageJPanel();
        jFrame.add(manualResizeableImageJPanel);


        jFrame.setVisible(true);
        try
        {
            //create client socket, connect to server
            Socket clientSocket=new Socket("192.168.2.8",3333);
            //create output stream attached to socket
            DataOutputStream outToServer=new DataOutputStream(clientSocket.getOutputStream());

            // outToServer.writeBytes("aaaaa");

            System.out.print("Command : ");

            //create input stream attached to socket
            InputStream inFromServer=clientSocket.getInputStream();
            for(long sum=0, cnt=0;true;)
            {
                int buf[]=new int[4];
                int len=0;
                for(;(buf[len]=inFromServer.read())!=-1;len=(len+1)%4)
                {
                    if(buf[(len+4-3)%4]==0x00&&buf[(len+4-2)%4]==0xFF&&buf[(len+4-1)%4]==0x01&&buf[(len)%4]==0x01)
                    {
                        // System.out.println("head");
                        break;
                    }
                }
                BufferedImage image=new BufferedImage(188,120,BufferedImage.TYPE_INT_RGB);
                long startTime=System.currentTimeMillis();
                for(int i=0;i<120;++i)
                {
                    for(int j=0;j<188;++j)
                    {
                        int b=inFromServer.read();
                        image.setRGB(j,i,(((b)&0XFF)<<16)|(((b)&0XFF)<<8)|(((b)&0XFF)<<0));

                    }
                }
                manualResizeableImageJPanel.setImage(image);
                sum+=(System.currentTimeMillis()-startTime);
                ++cnt;
                System.out.println(""+(System.currentTimeMillis()-startTime)+"   "+cnt+"    "+sum/cnt);

            }
            // for(int displayBytes;(displayBytes=inFromServer.read())!=-1;)
            // {
            //// System.out.print(displayBytes);
            // receiveCnt++;
            // if(receiveCnt%1000==0)
            // System.out.println(""+receiveCnt/(System.currentTimeMillis()-startTime)*1000+"B/S");
            // }
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}
